import { provide, inject, defineComponent, createVNode, render, reactive, computed, onMounted, onBeforeUnmount, ref } from "vue";
export const DropdownItem = defineComponent({
    props:{
        label: String,
        icon: String
    },
    setup(props) {
        let {label, icon} = props
        let hide = inject('hide');
        return ()=> <div class="dropdown-item" onClick={hide}>
            <i class={[icon, 'iconfont']}></i>
            <span>{label}</span>
        </div>
    }
});
const DropdownComponent = defineComponent({
    props: {
        option: {type: Object}
    },
    setup(props,ctx) {
        const state = reactive({
            option: props.option,
            isShow: false,
            top: 0,
            left: 0
        })
        ctx.expose({
            showDropdown(option){
                state.option = option;
                state.isShow = true;
                let {top, left, height} = option.el.getBoundingClientRect();
                state.top = top + height;
                state.left = left;
            }
        })
        provide('hide', ()=> state.isShow = false)
        const classes = computed(()=>[
            'dropdown',
            {
                'dropdown-isShow': state.isShow
            }
        ])
        const styles = computed(()=>({
            top: state.top + 'px',
            left: state.left + 'px'
        }))
        const el = ref(null)
        const onmousedownDocumnet = (e) => {
            if(!el.value.contains(e.target)) { // 如果点击的是dropdown内部
                state.isShow = false;
            }
        }
        onMounted(()=> {
            // 事件的传递行为是先捕获再冒泡
            // 之前为了阻止事件传播 给block 都增加的stopPropagation
            document.body.addEventListener('mousedown', onmousedownDocumnet, true)
        })
        onBeforeUnmount(()=> {
            document.body.removeEventListener('mousedown', onmousedownDocumnet)
        })
        return ()=> {
            return <div class={classes.value} style={styles.value} ref={el}>
                {state.option.content()}
            </div>      
        }
    }
});
let vm;
export function $dropdown(option) {
   if(!vm){
    let el = document.createElement('div');
    // 将组件渲染
    let vm = createVNode(DropdownComponent, {option}); // 将组件渲染成虚拟节点
    // 这里需要将el渲染到页面中    
    document.body.appendChild((render(vm, el), el));    // 渲染成真实节点
    let { showDropdown } = vm.component.exposed;
    showDropdown(option);
   }
}